package com.itheima.springbootwebtlias.controller;

import com.itheima.springbootwebtlias.pojo.Emp;
import com.itheima.springbootwebtlias.pojo.Result;
import com.itheima.springbootwebtlias.service.EmpService;
import com.itheima.springbootwebtlias.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class LoginController {

    @Autowired
    private EmpService empService;

    //登录
    @PostMapping("/login")
    public Result login(@RequestBody Emp emp){
        //1.接收请求参数: 用户名, 密码
        //json格式: @RequestBody + 实体对象/map对象
        log.info("登录, 请求参数: {}", emp);

        //2.调用业务层Service的功能方法, 登录
        Emp resultEmp = empService.checkLogin(emp);

        Map map = new HashMap();
        map.put("id", resultEmp.getId());
        map.put("username", resultEmp.getUsername());
        map.put("name", resultEmp.getName());
        //登录成功，颁发令牌
        String jwtToken = JwtUtils.generateJwt(map);//生成jwt令牌
        map.put("token", jwtToken);                 //颁发令牌
        log.info("登录成功, 颁发令牌: {}", jwtToken);

        //3.封装响应结果
        return Result.success(map);//code=1, msg=success, data=?
    }


}
